﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using NHibernate;
using AVTracker.Models;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.SqlCommand;

namespace AVTracker.Data
{
    public class VehicleAdapter
    {

        static ISessionFactory _sessionFactory;
        static ISession OpenSession()
        {
            try
            {
                if (_sessionFactory == null) //not threadsafe
                { //SessionFactories are expensive, create only once
                    var configuration = new Configuration();
                    configuration.AddAssembly(Assembly.GetCallingAssembly());
                    _sessionFactory = configuration.BuildSessionFactory();
                }
            }
            catch (Exception)
            {
                throw;
            }

            return _sessionFactory.OpenSession();
        }


        public static IList<Vehicle> GetVehicles()
        {
            using (var session = OpenSession())
            {
                Vehicle vc = null;
                var result = session.QueryOver(() => vc)
                    .WithSubquery.WhereExists(QueryOver.Of<VehicleLocation>()
                        .Where(vl => vl.VehicleId == vc.VehicleId)
                        .Select(Projections.Id()))
                    .List();
                //.WhereRestrictionOn( v=> v.VehicleId ) ;

                return result;
            }
        }

        public static IList<VehicleLocation> GetVehicleLocation(long vehicleId)
        {
            using (var session = OpenSession())
            {
                var result = session.QueryOver<VehicleLocation>()
                    .Where(v=> v.VehicleId == vehicleId)
                    .OrderBy(v => v.ReceivedAt).Desc
                    .Take(1).List();

                return result;
            }
        }

    }
}